using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Application.Services;

namespace UniversalAdmin.Api.Controllers;

[ApiController]
[Route("api/v1/[controller]")]
[Authorize]
public class ChatController : ControllerBase
{
    private readonly IChatService _chatService;

    public ChatController(IChatService chatService)
    {
        _chatService = chatService;
    }

    [HttpPost("ask")]
    public async Task<IActionResult> AskQuestion([FromBody] ChatRequestDto dto)
    {
        try
        {
            var userId = GetCurrentUserId();
            var response = await _chatService.GetAnswerAsync(userId, dto.ConversationId, dto.Question);
            return Ok(response);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpGet("conversation/{conversationId}/history")]
    public async Task<IActionResult> GetConversationHistory(Guid conversationId)
    {
        try
        {
            var userId = GetCurrentUserId();
            var history = await _chatService.GetConversationHistoryAsync(userId, conversationId);
            return Ok(history);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpGet("conversations")]
    public async Task<IActionResult> GetConversations([FromQuery] int page = 1, [FromQuery] int pageSize = 10)
    {
        try
        {
            var userId = GetCurrentUserId();
            var conversations = await _chatService.GetConversationsAsync(userId, page, pageSize);
            return Ok(conversations);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpPost("conversation")]
    public async Task<IActionResult> CreateConversation([FromBody] CreateConversationDto dto)
    {
        try
        {
            var userId = GetCurrentUserId();
            var conversation = await _chatService.CreateConversationAsync(userId, dto.Title);
            return CreatedAtAction(nameof(GetConversations), new { id = conversation.Id }, conversation);
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpDelete("conversation/{conversationId}")]
    public async Task<IActionResult> DeleteConversation(Guid conversationId)
    {
        try
        {
            var userId = GetCurrentUserId();
            var success = await _chatService.DeleteConversationAsync(userId, conversationId);
            if (!success)
                return NotFound(new { message = "对话不存在" });
            return NoContent();
        }
        catch (Exception ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    private Guid GetCurrentUserId()
    {
        var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
        if (userIdClaim == null || !Guid.TryParse(userIdClaim.Value, out var userId))
        {
            throw new UnauthorizedAccessException("无法获取当前用户ID");
        }
        return userId;
    }
}